/**
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
#include "PointerTable.hpp"

//inicio: 0x10010, 0x100c8
//tamanho 0xb8 entradas, 2 bytes cada entrada

using namespace std;

/**********************************************************************************************/
PtrTable::PtrTable(const char* name, long start, int first):
_base(start)
{
	if(!(_rom = fopen(name, "rb")))
	{
		cout << "<!> Nao foi possivel abrir a rom \'" << name << "\'." << endl;
		exit(-1);
	}

	/** Lê toda a tabela de ponteiros, tendo como base paa o tamanho
		 o seu ponteiro inicial */
   for(int x = 0; x < 0xad; x++) {
      fseek(_rom, _base + x, SEEK_SET);
      int l = getc(_rom);
      fseek(_rom, 0xb7, SEEK_CUR);
      int h = getc(_rom);

		_tbl.push_back(((h << 8) | l ) & 0xffff);
   }

}

/**********************************************************************************************/
PtrTable::~PtrTable()
{
	fclose(_rom);
}

/**********************************************************************************************/
long PtrTable::get_bytes(int size)
{
	long ptr = 0;
	for(int x = 0; x < size; x++)
		ptr |= (getc(_rom) << (x  *8) );

	return ptr & 0xFFFFFFFF;
}

/**********************************************************************************************/
void PtrTable::print()
{
   cout << "*****************************************************************" << endl;
   cout << "Imprimindo Tabela" << endl;
   cout << "*****************************************************************" << endl;

	cout << "\t* " << dec  << _tbl.size() << " ponteiros." << endl;

	vector<long>::iterator entry = _tbl.begin();
	for( ; entry != _tbl.end(); entry++)
		cout << "\t0x" << hex << (*entry) + _base - 0x8000 << "(" << (*entry) << ")" << endl;
}

/**********************************************************************************************/
long PtrTable::size()
{
	return _tbl.size();
}

/**********************************************************************************************/
long PtrTable::get_ptr(string::size_type pos)
{
	if(pos > _tbl.size())
	{
		cout << "<!> Indice maior que o tamanho da tabela." << endl;
		return NOT_FOUND;
	}

	return _tbl[pos] + _base - 0x8000;
}
